package com.milo.config;

import com.sun.org.apache.xerces.internal.parsers.StandardParserConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.StandardPasswordEncoder;

/**
 * 配置类
 * @author Milo Lee
 * @date 2021-12-04 14:32
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder encoder (){
        return new StandardPasswordEncoder("123");
    }

    /***
     * 基于内存的用户存储
     * @author Milo Lee
     * @date 2021-12-04 14:48
     * @param auth 认证
     */
/*    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("milo")
                .password("123")
                .authorities("ROLE_USER")
                .and()
                .withUser("lee")
                .password("123")
                .authorities("ROLE_USER");

        //  auth.userDetailsService()

    }*/

    /***
     * 用来配置在Web级别该如何处理安全性
     * @author Milo Lee
     * @date 2021-12-04 15:36
     * @param http
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        //确保只有认证过的用户才能发起对“/design”和“/orders”的请求，而其他请求对所有用户均可用
        http.authorizeRequests()
                .antMatchers("/design", "/orders")
                .hasRole("ROLE_USER")
                .antMatchers("/", "/**").permitAll()
                .and()
                .formLogin()
                .loginPage("/login")
                //要监听对“/authenticate”的请求来处理登录信息的提交
                .loginProcessingUrl("/authenticate")
                //登录成功跳转页面
                .defaultSuccessUrl("/home")
                //用户名参数
                .usernameParameter("userName")
                //密码参数
                .passwordParameter("password")
                .and()
                //退出登录
                .logout()
                .logoutSuccessUrl("/");
    }
}
